

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=auto>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/img/fluid.png">
  <link rel="icon" href="/img/fluid.png">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="author" content="hz">
  <meta name="keywords" content="">
  
    <meta name="description" content="App的启动过程1、设置日志记录器，比较简单，不展开 2、根据BuildConfig.FLAVOR来输出不同的打印不同的版本信息 3、初始化dagger注入依赖 4、启动两个service，一个是加密服务，一个是自动上传服务，目测是为了后续的云盘、s3等上传 5、注册registerActivityLifecycleCallbacks，目的是为了激活机密服务，目测是为了放在App不在前台的时候锁住">
<meta property="og:type" content="article">
<meta property="og:title" content="Cryptomator-Android源码分析">
<meta property="og:url" content="https://blog.brzhang.club/2022/12/08/cryptomator-Android%E6%BA%90%E7%A0%81%E5%88%86%E6%9E%90/index.html">
<meta property="og:site_name" content="心随我动">
<meta property="og:description" content="App的启动过程1、设置日志记录器，比较简单，不展开 2、根据BuildConfig.FLAVOR来输出不同的打印不同的版本信息 3、初始化dagger注入依赖 4、启动两个service，一个是加密服务，一个是自动上传服务，目测是为了后续的云盘、s3等上传 5、注册registerActivityLifecycleCallbacks，目的是为了激活机密服务，目测是为了放在App不在前台的时候锁住">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2022-12-08T08:13:15.000Z">
<meta property="article:modified_time" content="2022-12-13T12:05:36.674Z">
<meta property="article:author" content="hz">
<meta property="article:tag" content="Android">
<meta name="twitter:card" content="summary_large_image">
  
  
    <meta name="referrer" content="no-referrer-when-downgrade">
  
  
  <title>Cryptomator-Android源码分析 - 心随我动</title>

  <link  rel="stylesheet" href="https://lib.baomitu.com/twitter-bootstrap/4.6.1/css/bootstrap.min.css" />



  <link  rel="stylesheet" href="https://lib.baomitu.com/github-markdown-css/4.0.0/github-markdown.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/hint.css/2.7.0/hint.min.css" />

  <link  rel="stylesheet" href="https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.css" />



<!-- 主题依赖的图标库，不要自行修改 -->
<!-- Do not modify the link that theme dependent icons -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_hj8rtnfg7um.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_lbnruvf0jn.css">


<link  rel="stylesheet" href="/css/main.css" />


  <link id="highlight-css" rel="stylesheet" href="/css/highlight.css" />
  
    <link id="highlight-css-dark" rel="stylesheet" href="/css/highlight-dark.css" />
  




  <script id="fluid-configs">
    var Fluid = window.Fluid || {};
    Fluid.ctx = Object.assign({}, Fluid.ctx)
    var CONFIG = {"hostname":"blog.brzhang.club","root":"/","version":"1.9.5","typing":{"enable":true,"typeSpeed":70,"cursorChar":"_","loop":false,"scope":[]},"anchorjs":{"enable":true,"element":"h1,h2,h3,h4,h5,h6","placement":"left","visible":"hover","icon":""},"progressbar":{"enable":true,"height_px":3,"color":"#29d","options":{"showSpinner":false,"trickleSpeed":100}},"code_language":{"enable":true,"default":"TEXT"},"copy_btn":true,"image_caption":{"enable":true},"image_zoom":{"enable":true,"img_url_replace":["",""]},"toc":{"enable":true,"placement":"left","headingSelector":"h1,h2,h3,h4,h5,h6","collapseDepth":0},"lazyload":{"enable":true,"loading_img":"/img/loading.gif","onlypost":false,"offset_factor":2},"web_analytics":{"enable":false,"follow_dnt":true,"baidu":null,"google":{"measurement_id":null},"tencent":{"sid":null,"cid":null},"woyaola":null,"cnzz":null,"leancloud":{"app_id":null,"app_key":null,"server_url":null,"path":"window.location.pathname","ignore_local":false}},"search_path":"/local-search.xml","include_content_in_search":true};

    if (CONFIG.web_analytics.follow_dnt) {
      var dntVal = navigator.doNotTrack || window.doNotTrack || navigator.msDoNotTrack;
      Fluid.ctx.dnt = dntVal && (dntVal.startsWith('1') || dntVal.startsWith('yes') || dntVal.startsWith('on'));
    }
  </script>
  <script  src="/js/utils.js" ></script>
  <script  src="/js/color-schema.js" ></script>
  


  
<meta name="generator" content="Hexo 6.3.0"></head>


<body>
  

  <header>
    

<div class="header-inner" style="height: 30vh;">
  <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand" href="/">
      <strong>Brzhang</strong>
    </a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/">
                <i class="iconfont icon-home-fill"></i>
                <span>首页</span>
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/archives/">
                <i class="iconfont icon-archive-fill"></i>
                <span>归档</span>
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/categories/">
                <i class="iconfont icon-category-fill"></i>
                <span>分类</span>
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/tags/">
                <i class="iconfont icon-tags-fill"></i>
                <span>标签</span>
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/about/">
                <i class="iconfont icon-user-fill"></i>
                <span>关于</span>
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" target="_self" href="javascript:;" data-toggle="modal" data-target="#modalSearch" aria-label="Search">
              <i class="iconfont icon-search"></i>
            </a>
          </li>
          
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" target="_self" href="javascript:;" aria-label="Color Toggle">
              <i class="iconfont icon-dark" id="color-toggle-icon"></i>
            </a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

  

<div id="banner" class="banner" parallax=true
     style="background: url('/img/default.png') no-repeat center center; background-size: cover;">
  <div class="full-bg-img">
    <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
      <div class="banner-text text-center fade-in-up">
        <div class="h2">
          
            <span id="subtitle" data-typed-text="Cryptomator-Android源码分析"></span>
          
        </div>

        
          
  <div class="mt-3">
    
      <span class="post-meta mr-2">
        <i class="iconfont icon-author" aria-hidden="true"></i>
        hz
      </span>
    
    
      <span class="post-meta">
        <i class="iconfont icon-date-fill" aria-hidden="true"></i>
        <time datetime="2022-12-08 16:13" pubdate>
          2022年12月8日 下午
        </time>
      </span>
    
  </div>

  <div class="mt-1">
    
      <span class="post-meta mr-2">
        <i class="iconfont icon-chart"></i>
        
          14k 字
        
      </span>
    

    
      <span class="post-meta mr-2">
        <i class="iconfont icon-clock-fill"></i>
        
        
        
          116 分钟
        
      </span>
    

    
    
      
        <span id="busuanzi_container_page_pv" style="display: none">
          <i class="iconfont icon-eye" aria-hidden="true"></i>
          <span id="busuanzi_value_page_pv"></span> 次
        </span>
        
      
    
  </div>


        
      </div>

      
    </div>
  </div>
</div>

</div>

  </header>

  <main>
    
      

<div class="container-fluid nopadding-x">
  <div class="row nomargin-x">
    <div class="side-col d-none d-lg-block col-lg-2">
      
  <aside class="sidebar" style="padding-left: 2rem; margin-right: -1rem">
    <div id="toc">
  <p class="toc-header">
    <i class="iconfont icon-list"></i>
    <span>目录</span>
  </p>
  <div class="toc-body" id="toc-body"></div>
</div>



  </aside>


    </div>

    <div class="col-lg-8 nopadding-x-md">
      <div class="container nopadding-x-md" id="board-ctn">
        <div id="board">
          <article class="post-content mx-auto">
            <h1 id="seo-header">Cryptomator-Android源码分析</h1>
            
            
              <div class="markdown-body">
                
                <h4 id="App的启动过程"><a href="#App的启动过程" class="headerlink" title="App的启动过程"></a>App的启动过程</h4><p>1、设置日志记录器，比较简单，不展开</p>
<p>2、根据BuildConfig.FLAVOR来输出不同的打印不同的版本信息</p>
<p>3、初始化dagger注入依赖</p>
<p>4、启动两个service，一个是加密服务，一个是自动上传服务，目测是为了后续的云盘、s3等上传</p>
<p>5、注册registerActivityLifecycleCallbacks，目的是为了激活机密服务，目测是为了放在App不在前台的时候锁住保险库。</p>
<p>6、设置主题颜色，三种，跟随系统，暗系，白系。</p>
<p>7、清理缓存，这是一个AsyncTask，因此不会卡UI线程，具体是做了 <code>cleanupDir(context.cacheDir)</code>。</p>
<p>8、给RxJava添加一个统一的错误处理，啥都没干，只打印了日志。</p>
<p>至此，cryptomator-Android的启动过程就完成了，这里难点在于dagger注入各种依赖，大可不必细看，只知道，需要使用到各种module的时候，dagger会自动帮注入好就可以。</p>
<p>需要稍微了解一下kotlin的一些语法，如:</p>
<figure class="highlight kotlin"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><code class="hljs kotlin"><span class="hljs-comment">//回调lambda简化</span><br>mView.setEventListener(<span class="hljs-keyword">object</span>:Listenser&#123;<br>	<span class="hljs-keyword">public</span> void onSuccess(Data <span class="hljs-keyword">data</span>)&#123;<br>    <span class="hljs-comment">//todo</span><br>  &#125;<br>&#125;)<br><span class="hljs-comment">////可简化为</span><br>mView.setEventListener&#123;<br>  <span class="hljs-comment">//todo</span><br>&#125;<br><br><span class="hljs-comment">//内联扩展函数,最重要的事可以简化多次判空操作。</span><br>a?let&#123;<br>  it.do1()<br>  it.do2()<br>  it.do3()<br>&#125;<br><span class="hljs-comment">/// 类似的内联还有 with操作，和js的with有点类似，可以避免频繁的写多次context</span><br><br><span class="hljs-comment">// use 操作，自带try catch ，fanlly 中 自带close操作，简直是流操作的福音</span><br><br></code></pre></td></tr></table></figure>



<h4 id="主activity的启动"><a href="#主activity的启动" class="headerlink" title="主activity的启动"></a>主activity的启动</h4><p>App启动之后，更具Android规则，打开的第一个activity应该是AndroidManifest中定义的启动的那个</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><code class="hljs xml"><span class="hljs-tag">&lt;<span class="hljs-name">activity</span></span><br><span class="hljs-tag">			<span class="hljs-attr">android:name</span>=<span class="hljs-string">&quot;.ui.activity.VaultListActivity&quot;</span></span><br><span class="hljs-tag">			<span class="hljs-attr">android:exported</span>=<span class="hljs-string">&quot;true&quot;</span></span><br><span class="hljs-tag">			<span class="hljs-attr">android:theme</span>=<span class="hljs-string">&quot;@style/AppTheme.Starting&quot;</span></span><br><span class="hljs-tag">			<span class="hljs-attr">android:windowSoftInputMode</span>=<span class="hljs-string">&quot;adjustPan&quot;</span>&gt;</span><br>			<span class="hljs-tag">&lt;<span class="hljs-name">intent-filter</span>&gt;</span><br>				<span class="hljs-tag">&lt;<span class="hljs-name">action</span> <span class="hljs-attr">android:name</span>=<span class="hljs-string">&quot;android.intent.action.MAIN&quot;</span> /&gt;</span><br><br>				<span class="hljs-tag">&lt;<span class="hljs-name">category</span> <span class="hljs-attr">android:name</span>=<span class="hljs-string">&quot;android.intent.category.LAUNCHER&quot;</span> /&gt;</span><br>			<span class="hljs-tag">&lt;/<span class="hljs-name">intent-filter</span>&gt;</span><br><span class="hljs-tag">&lt;/<span class="hljs-name">activity</span>&gt;</span><br></code></pre></td></tr></table></figure>

<p>因此，毫无疑问，应该跑到这个入口页里面瞅瞅做了啥。</p>
<p>VaultListActivity继承自BaseActivity，因此，一般来讲一些公共的逻辑讲都会放在基类中来处理，直接看onCreate方法：</p>
<p>1、埋个日志，表示进入onCreate，简单不介绍</p>
<p>2、initializeDagger，使用dagger进行依赖注入,</p>
<p>3、初始化界面，可以看到布局是一个空壳子，界面的渲染全靠fragment。</p>
<figure class="highlight kotlin"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><code class="hljs kotlin"><span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">onCreate</span><span class="hljs-params">(savedInstanceState: <span class="hljs-type">Bundle</span>?)</span></span> &#123;<br>		<span class="hljs-keyword">super</span>.onCreate(savedInstanceState)<br>		logLifecycle(<span class="hljs-string">&quot;onCreate&quot;</span>)<br><br>		<span class="hljs-keyword">this</span>.activityComponent = initializeDagger()<br><br>		javaClass.getAnnotation(Activity::<span class="hljs-keyword">class</span>.java)?.let &#123;<br>			setContentView(getContentLayout(it))<br><br>			Activities.setIntent(<span class="hljs-keyword">this</span>)<br>			<span class="hljs-keyword">this</span>.presenter = Activities.initializePresenter(<span class="hljs-keyword">this</span>)<br>			afterIntentInjected()<br><br>			<span class="hljs-keyword">if</span> (savedInstanceState != <span class="hljs-literal">null</span>) &#123;<br>				restoreState(savedInstanceState)<br>			&#125;<br>			<span class="hljs-comment">//</span><br>			setupView()<br>			setupPresenter()<br><br>			<span class="hljs-keyword">if</span> (savedInstanceState == <span class="hljs-literal">null</span>) &#123;<br>				createAndAddFragment()<br>			&#125;<br><br>			currentDialog = supportFragmentManager.findFragmentByTag(ACTIVE_DIALOG) <span class="hljs-keyword">as</span>? DialogFragment<br>			closeDialogOnResume = currentDialog != <span class="hljs-literal">null</span><br>		&#125; ?: Timber.tag(<span class="hljs-string">&quot;BaseActivity&quot;</span>).e(<span class="hljs-string">&quot;Failed to initialize Activity because config is null&quot;</span>)<br>	&#125;<br></code></pre></td></tr></table></figure>

<p>setupView中使用</p>
<figure class="highlight kotlin"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><code class="hljs kotlin"><span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">setupView</span><span class="hljs-params">()</span></span> &#123;<br>		setupToolbar()<br>		vaultListPresenter.prepareView()<br>		activityRootView.setOnFilteredTouchEventForSecurityListener(<span class="hljs-keyword">object</span> : Listener &#123;<br>			<span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">onFilteredTouchEventForSecurity</span><span class="hljs-params">()</span></span> &#123;<br>				vaultListPresenter.onFilteredTouchEventForSecurity()<br>			&#125;<br>		&#125;)<br><br>		<span class="hljs-keyword">if</span> (stopEditFilePressed() &amp;&amp; sharedPreferencesHandler.keepUnlockedWhileEditing()) &#123;<br>			hideNotification()<br>			unSuspendLock()<br>		&#125;<br>	&#125;<br></code></pre></td></tr></table></figure>

<p>vaultListPresenter.prepareView() 去准备view，这个时候，会触发checkLicense()。如果没有License，会告诉你去填license。这里绕过license的检测比较简单，直接注释去检测就好，下面一小节讲解一下license的检查策略。</p>
<figure class="highlight kotlin"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><code class="hljs kotlin"><span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">prepareView</span><span class="hljs-params">()</span></span> &#123;<br>		<span class="hljs-keyword">if</span> (!sharedPreferencesHandler.isScreenLockDialogAlreadyShown) &#123;<br>			<span class="hljs-keyword">val</span> keyguardManager = context().getSystemService(Context.KEYGUARD_SERVICE) <span class="hljs-keyword">as</span> KeyguardManager<br>			<span class="hljs-keyword">if</span> (!keyguardManager.isKeyguardSecure) &#123;<br>				view?.showDialog(AskForLockScreenDialog.newInstance())<br>			&#125;<br>			sharedPreferencesHandler.setScreenLockDialogAlreadyShown()<br>		&#125;<br><br>		sharedPreferencesHandler.vaultsRemovedDuringMigration()?.let &#123;<br>			<span class="hljs-keyword">val</span> cloudNameString = getString(CloudTypeModel.valueOf(CloudType.valueOf(it.first)).displayNameResource)<br>			view?.showDialog(VaultsRemovedDuringMigrationDialog.newInstance(Pair(cloudNameString, it.second)))<br>			sharedPreferencesHandler.vaultsRemovedDuringMigration(<span class="hljs-literal">null</span>)<br>		&#125;<br><br>  	<span class="hljs-comment">// 注释，别去检查了</span><br>		<span class="hljs-comment">//checkLicense()</span><br><br>		<span class="hljs-keyword">if</span> (sharedPreferencesHandler.usePhotoUpload()) &#123;<br>			checkLocalStoragePermissionRegardingAutoUpload()<br>		&#125;<br>	&#125;<br></code></pre></td></tr></table></figure>



<p>有的话就要开始走渲染界面了。</p>
<p>接下来走到onResume逻辑中看看</p>
<p>1、埋点日志，表示进入onResume，简单也不在介绍</p>
<p>2、设置被覆盖时不响应touches事件</p>
<p>3、设置安全策略，禁止录屏</p>
<p>4、判断是否没有打开的保险库，如果没有，就关闭当前打开的图片呀，文本文件之类的资源，一种保护。<strong>主要就是防止锁屏了，锁屏之前在浏览文件，打开还会看到文件</strong>。</p>
<p>所以第一个启动的activity的视图展示任务就落到了VaultListFragment上了。</p>
<p>整个布局就是一个RecyclerView展示的列表，然后在onResume的时候，调用presenter去load保险库列表</p>
<figure class="highlight kotlin"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><code class="hljs kotlin"><span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">onResume</span><span class="hljs-params">()</span></span> &#123;<br>		<span class="hljs-keyword">super</span>.onResume()<br>		vaultListPresenter.loadVaultList()<br>&#125;<br></code></pre></td></tr></table></figure>

<p>至此其实进入保险库的整个流程就完毕了。</p>
<h4 id="license检查"><a href="#license检查" class="headerlink" title="license检查"></a>license检查</h4><p>前面提到应用主界面会触发license的检查，其检查逻辑是除了Google player安装的版本，就会进入license检查环境，因此，这里可以看到版本的打包是使用了<code>BuildConfig.FLAVOR </code>特性。检查的逻辑是</p>
<figure class="highlight kotlin"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><code class="hljs kotlin"><span class="hljs-keyword">private</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">checkLicense</span><span class="hljs-params">()</span></span> &#123;<br>		<span class="hljs-keyword">if</span> (BuildConfig.FLAVOR == <span class="hljs-string">&quot;apkstore&quot;</span> || BuildConfig.FLAVOR == <span class="hljs-string">&quot;fdroid&quot;</span> || BuildConfig.FLAVOR == <span class="hljs-string">&quot;lite&quot;</span>) &#123;<br>			licenseCheckUseCase <span class="hljs-comment">//</span><br>				.withLicense(<span class="hljs-string">&quot;&quot;</span>) <span class="hljs-comment">//</span><br>				.run(<span class="hljs-keyword">object</span> : NoOpResultHandler&lt;LicenseCheck&gt;() &#123;<br>					<span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">onSuccess</span><span class="hljs-params">(licenseCheck: <span class="hljs-type">LicenseCheck</span>)</span></span> &#123;<br>						<span class="hljs-keyword">if</span> (BuildConfig.FLAVOR == <span class="hljs-string">&quot;apkstore&quot;</span> &amp;&amp; sharedPreferencesHandler.doUpdate()) &#123;<br>							checkForAppUpdates()<br>						&#125;<br>					&#125;<br><br>					<span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">onError</span><span class="hljs-params">(e: <span class="hljs-type">Throwable</span>)</span></span> &#123;<br>						<span class="hljs-keyword">val</span> license = <span class="hljs-keyword">if</span> (e <span class="hljs-keyword">is</span> LicenseNotValidException) &#123;<br>							e.license<br>						&#125; <span class="hljs-keyword">else</span> &#123;<br>							<span class="hljs-string">&quot;&quot;</span><br>						&#125;<br>						<span class="hljs-keyword">val</span> intent = Intent(context(), LicenseCheckActivity::<span class="hljs-keyword">class</span>.java)<br>						intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK<br>						intent.<span class="hljs-keyword">data</span> = Uri.parse(String.format(<span class="hljs-string">&quot;app://cryptomator/%s&quot;</span>, license))<br><br>						<span class="hljs-keyword">try</span> &#123;<br>							context().startActivity(intent)<br>						&#125; <span class="hljs-keyword">catch</span> (e: ActivityNotFoundException) &#123;<br>							Toast.makeText(context(), <span class="hljs-string">&quot;Please contact the support.&quot;</span>, Toast.LENGTH_LONG).show()<br>							finish()<br>						&#125;<br>					&#125;<br>				&#125;)<br>		&#125;<br>&#125;<br></code></pre></td></tr></table></figure>

<p>1、如果没有传入license，就会使用本地存储（SQLlite）中的license来进行验证。</p>
<p>2、验证的主要逻辑就是使用公钥来解密license，看看是否可以解密出来，如果可以，就证明license是人家私钥加密的合法license，否则就是伪造的。</p>
<figure class="highlight kotlin"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><code class="hljs kotlin"><span class="hljs-keyword">private</span> static <span class="hljs-keyword">final</span> String ANDROID_PUB_KEY = <span class="hljs-string">&quot;MIGbMBAGByqGSM49AgEGBSuBBAAjA4GGAAQBcnb81CfNeL3qBVFMx/yRfm1Y1yib&quot;</span> + <span class="hljs-comment">//</span><br>			<span class="hljs-string">&quot;ajIJkV1s82AQt+mOl4+Kub64wq1OCgBVwWUlKwqgnyF39nmkoXEjakRPFngBzg2J&quot;</span> + <span class="hljs-comment">//</span><br>			<span class="hljs-string">&quot;zo4UR0B7OYmn0uGf3K+zQfxKnNMxGVPtlzE8j9Nqz/dm2YvYLLVwvTSDQX/GaxoP&quot;</span> + <span class="hljs-comment">//</span><br>			<span class="hljs-string">&quot;/EH84Hupw2wuU7qAaFU=&quot;</span>;<br><span class="hljs-keyword">final</span> Claims claims = <br>Jwts.parserBuilder().setSigningKey(getPublicKey(ANDROID_PUB_KEY)).build().parseClaimsJws(license).getBody();<br>			<span class="hljs-keyword">return</span> claims::getSubject;<br></code></pre></td></tr></table></figure>

<p>原理很简单，就是利用了<strong>非对称加解密</strong>。</p>
<h4 id="添加一个保险库"><a href="#添加一个保险库" class="headerlink" title="添加一个保险库"></a>添加一个保险库</h4><p>进入系统之后，就是看怎么添加一个保险库，保险库的添加有两种方式；1、从0创建一个。2、继承至一个已有的。</p>
<figure class="highlight kotlin"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><code class="hljs kotlin"><span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">onAddExistingVault</span><span class="hljs-params">()</span></span> &#123;<br>		addExistingVaultWorkflow.start()<br>&#125;<br><br><span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">onCreateVault</span><span class="hljs-params">()</span></span> &#123;<br>  	createNewVaultWorkflow.start()<br>&#125;<br></code></pre></td></tr></table></figure>

<p>直接看从0开始创建的流程：</p>
<p>1、点击新建一个vault的话，会进入一个选择CloudType的界面，有[Dropbox，Google Drive，OneDrive等等]，当然还包括本地。</p>
<p>2、选择一个本地的玩一玩</p>
<p>3、进去是一个recycleView，如果之前添加过本地文件目录，那么是会有location列表的，初次创建是没有</p>
<p>4、点击底部的➕，会进入创建，创建会根据不同的CloudType进入不同的界面</p>
<figure class="highlight kotlin"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><code class="hljs kotlin"><span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">onAddConnectionClicked</span><span class="hljs-params">()</span></span> &#123;<br>		<span class="hljs-keyword">when</span> (selectedCloudType.<span class="hljs-keyword">get</span>()) &#123;<br>			CloudTypeModel.ONEDRIVE -&gt; addOnedriveCloud()<br>			CloudTypeModel.WEBDAV -&gt; requestActivityResult(ActivityResultCallbacks.addChangeMultiCloud(), Intents.webDavAddOrChangeIntent())<br>			CloudTypeModel.PCLOUD -&gt; requestActivityResult(ActivityResultCallbacks.pCloudAuthenticationFinished(), Intents.authenticatePCloudIntent())<br>			CloudTypeModel.S3 -&gt; requestActivityResult(ActivityResultCallbacks.addChangeMultiCloud(), Intents.s3AddOrChangeIntent())<br>			CloudTypeModel.LOCAL -&gt; openDocumentTree()<br>		&#125;<br>	&#125;<br></code></pre></td></tr></table></figure>

<p>5、openDocumentTree就是拿到一个通过一个intent打开文件管理，然后返回一个contentProvider的uri，长这样<code>content://com.android.externalstorage.documents/tree/primary%3A11111</code>，随后保存到书库中</p>
<figure class="highlight kotlin"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><code class="hljs kotlin"><span class="hljs-keyword">public</span> void execute() throws BackendException &#123;<br>		<span class="hljs-keyword">if</span> (cloudExists(cloud)) &#123;<br>			<span class="hljs-keyword">throw</span> new CloudAlreadyExistsException();<br>		&#125;<br><br>		<span class="hljs-keyword">if</span> (cloud.persistent()) &#123;<br>			cloudRepository.store(cloud);<br>		&#125; <span class="hljs-keyword">else</span> &#123;<br>			<span class="hljs-keyword">throw</span> new FatalBackendException(<span class="hljs-string">&quot;Can&#x27;t change cloud because it&#x27;s not persistent&quot;</span>);<br>		&#125;<br>	&#125;<br></code></pre></td></tr></table></figure>

<p>6、点击一个location之后，会进入CreateVaultActivity中。</p>
<figure class="highlight kotlin"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><code class="hljs kotlin">void onCloudServiceChosen(SerializableResult&lt;CloudModel&gt; result) &#123;<br>		onCloudServiceChosen(result.getResult());<br>	&#125;<br><br>	<span class="hljs-keyword">private</span> void onCloudServiceChosen(CloudModel cloud) &#123;<br>		presenter().getView().showProgress(ProgressModel.GENERIC);<br>		getRootFolderUseCase <span class="hljs-comment">//</span><br>				.withCloud(cloud.toCloud()) <span class="hljs-comment">//</span><br>				.run(((ChooseCloudServicePresenter) presenter()).new ProgressCompletingResultHandler&lt;CloudFolder&gt;() &#123;<br>					<span class="hljs-meta">@Override</span><br>					<span class="hljs-keyword">public</span> void onSuccess(CloudFolder cloudFolder) &#123;<br>						state().cloudRoot = cloudFolder;<br>						chain(createVaultIntent(), SerializableResultCallbacks.nameEntered());<br>					&#125;<br><br>					<span class="hljs-meta">@Override</span><br>					<span class="hljs-keyword">public</span> void onError(Throwable e) &#123;<br>						<span class="hljs-keyword">if</span> (!authenticationExceptionHandler.handleAuthenticationException( <span class="hljs-comment">//</span><br>								presenter(), <span class="hljs-comment">//</span><br>								e, <span class="hljs-comment">//</span><br>								ActivityResultCallbacks.onCloudServiceAuthenticated())) &#123;<br>							<span class="hljs-keyword">super</span>.onError(e);<br>						&#125;<br>					&#125;<br>				&#125;);<br>	&#125;<br></code></pre></td></tr></table></figure>

<p>7、一进入，vaultNameEditText.requestFocus()就开始让你输入vaultName，确认之后，进入密码输入界面，密码是有强度的，使用了一个开源库zxvcbn来验证密码强度，而且排除了一些关键字作为密码</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><code class="hljs java">RxTextView.textChanges(passwordInput) <span class="hljs-comment">//</span><br>				.observeOn(Schedulers.computation()) <span class="hljs-comment">//</span><br>				.map(password -&gt; PasswordStrength.Companion.forPassword(password.toString(), SANITIZED_INPUTS)) <span class="hljs-comment">//</span><br>				.observeOn(AndroidSchedulers.mainThread()) <span class="hljs-comment">//</span><br>				.subscribe(strength -&gt; &#123;<br>					strengthMeter.getProgressDrawable().setColorFilter(ResourceHelper.Companion.getColor(strength.getColor()), PorterDuff.Mode.SRC_IN);<br>					strengthLabel.setText(strength.getDescription());<br>					strengthMeter.setProgress(strength.getScore() + <span class="hljs-number">1</span>);<br>					button.setEnabled(strength.getScore() &gt; PasswordStrength.EXTREMELY_WEAK.getScore());<br>				&#125;);<br></code></pre></td></tr></table></figure>

<p>输入强度比较OK的密码之后，就到了创建vault的最后环节了</p>
<figure class="highlight kotlin"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><code class="hljs kotlin"><span class="hljs-keyword">public</span> Vault execute() throws BackendException &#123;<br>		CloudFolder vaultFolder = cloudContentRepository.folder(folder, vaultName);<br>		vaultFolder = cloudContentRepository.create(vaultFolder);<br>   <span class="hljs-comment">// 带着输入的密码过来创建vaultFolder</span><br>		cloudRepository.create(vaultFolder, password);<br>		<span class="hljs-keyword">return</span> vaultRepository.store(aVault() <span class="hljs-comment">//</span><br>				.thatIsNew() <span class="hljs-comment">//</span><br>				.withNamePathAndCloudFrom(vaultFolder) <span class="hljs-comment">//</span><br>				.withPosition(vaultRepository.vaults().size()) <span class="hljs-comment">//</span><br>				.build());<br>	&#125;<br></code></pre></td></tr></table></figure>

<p>create的真正实现在于</p>
<figure class="highlight kotlin"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><code class="hljs kotlin"><span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">create</span><span class="hljs-params">(location: <span class="hljs-type">CloudFolder</span>, password: <span class="hljs-type">CharSequence</span>?, vaultConfigBuilder: <span class="hljs-type">VaultConfigBuilder</span>)</span></span> &#123;<br>		<span class="hljs-comment">// 1. write masterkey:</span><br>		<span class="hljs-keyword">val</span> masterkey = Masterkey.generate(secureRandom)<br>		<span class="hljs-keyword">try</span> &#123;<br>			ByteArrayOutputStream().use &#123; <span class="hljs-keyword">data</span> -&gt;<br>				MasterkeyFileAccess(CryptoConstants.PEPPER, secureRandom).persist(masterkey, <span class="hljs-keyword">data</span>, password, CryptoConstants.DEFAULT_MASTERKEY_FILE_VERSION)<br>				cloudContentRepository.write(legacyMasterkeyFile(location), from(<span class="hljs-keyword">data</span>.toByteArray()), ProgressAware.NO_OP_PROGRESS_AWARE_UPLOAD, <span class="hljs-literal">false</span>, <span class="hljs-keyword">data</span>.size().toLong())<br>			&#125;<br>		&#125; <span class="hljs-keyword">catch</span> (e: IOException) &#123;<br>			<span class="hljs-keyword">throw</span> FatalBackendException(<span class="hljs-string">&quot;Failed to write masterkey&quot;</span>, e)<br>		&#125;<br><br>		<span class="hljs-comment">// 2. initialize vault:</span><br>		<span class="hljs-keyword">val</span> vaultConfig = vaultConfigBuilder <span class="hljs-comment">//</span><br>			.vaultFormat(CryptoConstants.MAX_VAULT_VERSION) <span class="hljs-comment">//</span><br>			.cipherCombo(CryptoConstants.DEFAULT_CIPHER_COMBO) <span class="hljs-comment">//</span><br>			.keyId(URI.create(String.format(<span class="hljs-string">&quot;%s:%s&quot;</span>, CryptoConstants.MASTERKEY_SCHEME, CryptoConstants.MASTERKEY_FILE_NAME))) <span class="hljs-comment">//</span><br>			.shorteningThreshold(CryptoConstants.DEFAULT_MAX_FILE_NAME) <span class="hljs-comment">//</span><br>			.build()<br>		<span class="hljs-keyword">val</span> encodedVaultConfig = vaultConfig.toToken(masterkey.encoded).toByteArray(StandardCharsets.UTF_8)<br>		<span class="hljs-keyword">val</span> vaultFile = cloudContentRepository.file(location, CryptoConstants.VAULT_FILE_NAME)<br>		cloudContentRepository.write(vaultFile, from(encodedVaultConfig), ProgressAware.NO_OP_PROGRESS_AWARE_UPLOAD, <span class="hljs-literal">false</span>, encodedVaultConfig.size.toLong())<br><br>		<span class="hljs-comment">// 3. create root folder:</span><br>		createRootFolder(location, cryptorFor(masterkey, vaultConfig.cipherCombo))<br>	&#125;<br></code></pre></td></tr></table></figure>

<p>1、写了一个Masterkey，写一个masterkey.cryptomator</p>
<p>2、初始化一个vault，写一个vault.cryptomator</p>
<p>3、初始化根目录，支持一个保险库初始化完毕。</p>
<h4 id="文件加密机制"><a href="#文件加密机制" class="headerlink" title="文件加密机制"></a>文件加密机制</h4><p>要添加文件，就需要先打开保险库，然后在保险库中添加文件。</p>
<p>1、因为我们打开的是本地保险库，因此会根据这个保险库的找到目录下的vault.cryptomator，然后从里面读出，内容，用来匹配用户输入的密码，其原理就是重放生成masterkey.cryptomator的过程，匹配看是否一致。</p>
<figure class="highlight kotlin"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><code class="hljs kotlin"><span class="hljs-keyword">private</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">unlockVault</span><span class="hljs-params">(vaultModel: <span class="hljs-type">VaultModel</span>)</span></span> &#123;<br>		<span class="hljs-keyword">if</span> (canUseBiometricOn(vaultModel)) &#123;<br>			<span class="hljs-keyword">if</span> (startedUsingPrepareUnlock) &#123;<br>				startPrepareUnlockUseCase(vaultModel.toVault())<br>			&#125;<br>			view?.showBiometricDialog(vaultModel)<br>		&#125; <span class="hljs-keyword">else</span> &#123;<br>			view?.showEnterPasswordDialog(vaultModel)<br>			startPrepareUnlockUseCase(vaultModel.toVault())<br>		&#125;<br>	&#125;<br></code></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-comment">/*******************************************************************************</span><br><span class="hljs-comment"> * Copyright (c) 2016 Sebastian Stenzel and others.</span><br><span class="hljs-comment"> * All rights reserved. This program and the accompanying materials</span><br><span class="hljs-comment"> * are made available under the terms of the accompanying LICENSE.txt.</span><br><span class="hljs-comment"> *</span><br><span class="hljs-comment"> * Contributors:</span><br><span class="hljs-comment"> *     Sebastian Stenzel - initial API and implementation</span><br><span class="hljs-comment"> *******************************************************************************/</span><br><span class="hljs-keyword">package</span> org.cryptomator.cryptolib.common;<br><br><span class="hljs-keyword">import</span> java.io.IOException;<br><span class="hljs-keyword">import</span> java.nio.ByteBuffer;<br><span class="hljs-keyword">import</span> java.nio.channels.WritableByteChannel;<br><br><span class="hljs-keyword">import</span> org.cryptomator.cryptolib.api.Cryptor;<br><span class="hljs-keyword">import</span> org.cryptomator.cryptolib.api.FileHeader;<br><span class="hljs-keyword">import</span> org.cryptomator.cryptolib.common.ByteBuffers;<br><br><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">EncryptingWritableByteChannel</span> <span class="hljs-keyword">implements</span> <span class="hljs-title class_">WritableByteChannel</span> &#123;<br><br>	<span class="hljs-keyword">private</span> <span class="hljs-keyword">final</span> WritableByteChannel delegate;<br>	<span class="hljs-keyword">private</span> <span class="hljs-keyword">final</span> Cryptor cryptor;<br>	<span class="hljs-keyword">private</span> <span class="hljs-keyword">final</span> FileHeader header;<br>	<span class="hljs-keyword">private</span> <span class="hljs-keyword">final</span> ByteBuffer cleartextBuffer;<br><br>	<span class="hljs-keyword">private</span> <span class="hljs-type">boolean</span> <span class="hljs-variable">firstWrite</span> <span class="hljs-operator">=</span> <span class="hljs-literal">true</span>;<br>	<span class="hljs-keyword">private</span> <span class="hljs-type">long</span> <span class="hljs-variable">chunkNumber</span> <span class="hljs-operator">=</span> <span class="hljs-number">0</span>;<br><br>	<span class="hljs-keyword">public</span> <span class="hljs-title function_">EncryptingWritableByteChannel</span><span class="hljs-params">(WritableByteChannel destination, Cryptor cryptor)</span> &#123;<br>		<span class="hljs-built_in">this</span>.delegate = destination;<br>		<span class="hljs-built_in">this</span>.cryptor = cryptor;<br>		<span class="hljs-built_in">this</span>.header = cryptor.fileHeaderCryptor().create();<br>		<span class="hljs-built_in">this</span>.cleartextBuffer = ByteBuffer.allocate(cryptor.fileContentCryptor().cleartextChunkSize());<br>	&#125;<br><br>	<span class="hljs-meta">@Override</span><br>	<span class="hljs-keyword">public</span> <span class="hljs-type">boolean</span> <span class="hljs-title function_">isOpen</span><span class="hljs-params">()</span> &#123;<br>		<span class="hljs-keyword">return</span> delegate.isOpen();<br>	&#125;<br><br>	<span class="hljs-meta">@Override</span><br>	<span class="hljs-keyword">public</span> <span class="hljs-keyword">synchronized</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">close</span><span class="hljs-params">()</span> <span class="hljs-keyword">throws</span> IOException &#123;<br>		writeHeaderOnFirstWrite();<br>		encryptAndFlushBuffer();<br>		delegate.close();<br>	&#125;<br><br>	<span class="hljs-meta">@Override</span><br>	<span class="hljs-keyword">public</span> <span class="hljs-keyword">synchronized</span> <span class="hljs-type">int</span> <span class="hljs-title function_">write</span><span class="hljs-params">(ByteBuffer src)</span> <span class="hljs-keyword">throws</span> IOException &#123;<br>		writeHeaderOnFirstWrite();<br>		<span class="hljs-type">int</span> <span class="hljs-variable">result</span> <span class="hljs-operator">=</span> <span class="hljs-number">0</span>;<br>		<span class="hljs-keyword">while</span> (src.hasRemaining()) &#123;<br>			result += ByteBuffers.copy(src, cleartextBuffer);<br>			<span class="hljs-keyword">if</span> (!cleartextBuffer.hasRemaining()) &#123;<br>				encryptAndFlushBuffer();<br>			&#125;<br>		&#125;<br>		<span class="hljs-keyword">return</span> result;<br>	&#125;<br><br>  <span class="hljs-comment">/// 文件头加密</span><br>	<span class="hljs-keyword">private</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">writeHeaderOnFirstWrite</span><span class="hljs-params">()</span> <span class="hljs-keyword">throws</span> IOException &#123;<br>		<span class="hljs-keyword">if</span> (firstWrite) &#123;<br>			delegate.write(cryptor.fileHeaderCryptor().encryptHeader(header));<br>		&#125;<br>		firstWrite = <span class="hljs-literal">false</span>;<br>	&#125;<br><br>  <span class="hljs-comment">// 文件块加密</span><br>	<span class="hljs-keyword">private</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">encryptAndFlushBuffer</span><span class="hljs-params">()</span> <span class="hljs-keyword">throws</span> IOException &#123;<br>		cleartextBuffer.flip();<br>		<span class="hljs-keyword">if</span> (cleartextBuffer.hasRemaining()) &#123;<br>			<span class="hljs-type">ByteBuffer</span> <span class="hljs-variable">ciphertextBuffer</span> <span class="hljs-operator">=</span> cryptor.fileContentCryptor().encryptChunk(cleartextBuffer, chunkNumber++, header);<br>			delegate.write(ciphertextBuffer);<br>		&#125;<br>		cleartextBuffer.clear();<br>	&#125;<br><br>&#125;<br><br></code></pre></td></tr></table></figure>



<h4 id="各种云盘的添加"><a href="#各种云盘的添加" class="headerlink" title="各种云盘的添加"></a>各种云盘的添加</h4><h4 id="自动上锁机制"><a href="#自动上锁机制" class="headerlink" title="自动上锁机制"></a>自动上锁机制</h4><ol>
<li>前端使用sessionStorage换成虚拟切换的企业子id，保持tab下子企业id隔离。</li>
<li>所有站内以target&#x3D;”<em>blank</em>“新开页面逻辑检查下，已url参数的方式把子企业传过去，需要<strong>初始化切换的来源的</strong>子企业。</li>
<li>纯新开的新页面没有子企业信息，可以独立切换。</li>
<li>切换子企业的交互一致，封装组件，session状态维护。</li>
<li>接口通过全部传子企业id，后端做过滤，个别接口需要其他<strong>传通用参数</strong>，单独处理。</li>
</ol>

                
              </div>
            
            <hr/>
            <div>
              <div class="post-metas my-3">
  
    <div class="post-meta mr-3 d-flex align-items-center">
      <i class="iconfont icon-category"></i>
      

<span class="category-chains">
  
  
    
      <span class="category-chain">
        
  <a href="/categories/%E6%8A%80%E6%9C%AF/" class="category-chain-item">技术</a>
  
  

      </span>
    
  
</span>

    </div>
  
  
    <div class="post-meta">
      <i class="iconfont icon-tags"></i>
      
        <a href="/tags/Android/" class="print-no-link">#Android</a>
      
    </div>
  
</div>


              
  

  <div class="license-box my-3">
    <div class="license-title">
      <div>Cryptomator-Android源码分析</div>
      <div>https://blog.brzhang.club/2022/12/08/cryptomator-Android源码分析/</div>
    </div>
    <div class="license-meta">
      
        <div class="license-meta-item">
          <div>作者</div>
          <div>hz</div>
        </div>
      
      
        <div class="license-meta-item license-meta-date">
          <div>发布于</div>
          <div>2022年12月8日</div>
        </div>
      
      
      
        <div class="license-meta-item">
          <div>许可协议</div>
          <div>
            
              
              
                <a class="print-no-link" target="_blank" href="https://creativecommons.org/licenses/by/4.0/">
                  <span class="hint--top hint--rounded" aria-label="BY - 署名">
                    <i class="iconfont icon-by"></i>
                  </span>
                </a>
              
            
          </div>
        </div>
      
    </div>
    <div class="license-icon iconfont"></div>
  </div>



              
                <div class="post-prevnext my-3">
                  <article class="post-prev col-6">
                    
                    
                      <a href="/2023/04/17/%E7%B2%BE%E7%BE%8E%E6%A1%8C%E9%9D%A2%E7%AB%AFApp%E6%8E%A8%E8%8D%90/" title="精美桌面端App推荐">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">精美桌面端App推荐</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                      <a href="/2022/12/07/flutter%E8%93%9D%E7%9B%BE%E6%9E%84%E5%BB%BA%E6%8C%87%E5%8D%97/" title="Flutter蓝盾构建指南">
                        <span class="hidden-mobile">Flutter蓝盾构建指南</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </article>
                </div>
              
            </div>

            
  
  
    <article id="comments" lazyload>
      
  <script type="text/javascript">
    Fluid.utils.loadComments('#comments', function() {
      var light = 'github-light';
      var dark = 'github-dark';
      var schema = document.documentElement.getAttribute('data-user-color-scheme');
      if (schema === 'dark') {
        schema = dark;
      } else {
        schema = light;
      }
      window.UtterancesThemeLight = light;
      window.UtterancesThemeDark = dark;
      var s = document.createElement('script');
      s.setAttribute('src', 'https://utteranc.es/client.js');
      s.setAttribute('repo', 'bravekingzhang/bravekingzhang.github.io');
      s.setAttribute('issue-term', 'pathname');
      
      s.setAttribute('label', 'utterances');
      
      s.setAttribute('theme', schema);
      s.setAttribute('crossorigin', 'anonymous');
      document.getElementById('comments').appendChild(s);
    })
  </script>
  <noscript>Please enable JavaScript to view the comments</noscript>


    </article>
  


          </article>
        </div>
      </div>
    </div>

    <div class="side-col d-none d-lg-block col-lg-2">
      

    </div>
  </div>
</div>





  



  



  



  



  


  
  





  <script>
  Fluid.utils.createScript('https://lib.baomitu.com/mermaid/8.14.0/mermaid.min.js', function() {
    mermaid.initialize({"theme":"default"});

    Fluid.utils.listenDOMLoaded(function() {
      Fluid.events.registerRefreshCallback(function() {
        if ('mermaid' in window) {
          mermaid.init();
        }
      });
    });
  });
</script>






    

    
      <a id="scroll-top-button" aria-label="TOP" href="#" role="button">
        <i class="iconfont icon-arrowup" aria-hidden="true"></i>
      </a>
    

    
      <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v" for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>

    

    
  </main>

  <footer>
    <div class="footer-inner">
  
    <div class="footer-content">
       <a href="https://hexo.io" target="_blank" rel="nofollow noopener"><span>Hexo</span></a> <i class="iconfont icon-love"></i> <a href="https://github.com/fluid-dev/hexo-theme-fluid" target="_blank" rel="nofollow noopener"><span>Fluid</span></a> 
    </div>
  
  
    <div class="statistics">
  
  

  
    
      <span id="busuanzi_container_site_pv" style="display: none">
        总访问量 
        <span id="busuanzi_value_site_pv"></span>
         次
      </span>
    
    
      <span id="busuanzi_container_site_uv" style="display: none">
        总访客数 
        <span id="busuanzi_value_site_uv"></span>
         人
      </span>
    
    
  
</div>

  
  
  
</div>

  </footer>

  <!-- Scripts -->
  
  <script  src="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.js" ></script>
  <link  rel="stylesheet" href="https://lib.baomitu.com/nprogress/0.2.0/nprogress.min.css" />

  <script>
    NProgress.configure({"showSpinner":false,"trickleSpeed":100})
    NProgress.start()
    window.addEventListener('load', function() {
      NProgress.done();
    })
  </script>


<script  src="https://lib.baomitu.com/jquery/3.6.4/jquery.min.js" ></script>
<script  src="https://lib.baomitu.com/twitter-bootstrap/4.6.1/js/bootstrap.min.js" ></script>
<script  src="/js/events.js" ></script>
<script  src="/js/plugins.js" ></script>


  <script  src="https://lib.baomitu.com/typed.js/2.0.12/typed.min.js" ></script>
  <script>
    (function (window, document) {
      var typing = Fluid.plugins.typing;
      var subtitle = document.getElementById('subtitle');
      if (!subtitle || !typing) {
        return;
      }
      var text = subtitle.getAttribute('data-typed-text');
      
        typing(text);
      
    })(window, document);
  </script>




  
    <script  src="/js/img-lazyload.js" ></script>
  




  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/tocbot/4.20.1/tocbot.min.js', function() {
    var toc = jQuery('#toc');
    if (toc.length === 0 || !window.tocbot) { return; }
    var boardCtn = jQuery('#board-ctn');
    var boardTop = boardCtn.offset().top;

    window.tocbot.init(Object.assign({
      tocSelector     : '#toc-body',
      contentSelector : '.markdown-body',
      linkClass       : 'tocbot-link',
      activeLinkClass : 'tocbot-active-link',
      listClass       : 'tocbot-list',
      isCollapsedClass: 'tocbot-is-collapsed',
      collapsibleClass: 'tocbot-is-collapsible',
      scrollSmooth    : true,
      includeTitleTags: true,
      headingsOffset  : -boardTop,
    }, CONFIG.toc));
    if (toc.find('.toc-list-item').length > 0) {
      toc.css('visibility', 'visible');
    }

    Fluid.events.registerRefreshCallback(function() {
      if ('tocbot' in window) {
        tocbot.refresh();
        var toc = jQuery('#toc');
        if (toc.length === 0 || !tocbot) {
          return;
        }
        if (toc.find('.toc-list-item').length > 0) {
          toc.css('visibility', 'visible');
        }
      }
    });
  });
</script>


  <script src=https://lib.baomitu.com/clipboard.js/2.0.11/clipboard.min.js></script>

  <script>Fluid.plugins.codeWidget();</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/anchor-js/4.3.1/anchor.min.js', function() {
    window.anchors.options = {
      placement: CONFIG.anchorjs.placement,
      visible  : CONFIG.anchorjs.visible
    };
    if (CONFIG.anchorjs.icon) {
      window.anchors.options.icon = CONFIG.anchorjs.icon;
    }
    var el = (CONFIG.anchorjs.element || 'h1,h2,h3,h4,h5,h6').split(',');
    var res = [];
    for (var item of el) {
      res.push('.markdown-body > ' + item.trim());
    }
    if (CONFIG.anchorjs.placement === 'left') {
      window.anchors.options.class = 'anchorjs-link-left';
    }
    window.anchors.add(res.join(', '));

    Fluid.events.registerRefreshCallback(function() {
      if ('anchors' in window) {
        anchors.removeAll();
        var el = (CONFIG.anchorjs.element || 'h1,h2,h3,h4,h5,h6').split(',');
        var res = [];
        for (var item of el) {
          res.push('.markdown-body > ' + item.trim());
        }
        if (CONFIG.anchorjs.placement === 'left') {
          anchors.options.class = 'anchorjs-link-left';
        }
        anchors.add(res.join(', '));
      }
    });
  });
</script>


  
<script>
  Fluid.utils.createScript('https://lib.baomitu.com/fancybox/3.5.7/jquery.fancybox.min.js', function() {
    Fluid.plugins.fancyBox();
  });
</script>


  <script>Fluid.plugins.imageCaption();</script>

  
      <script>
        if (!window.MathJax) {
          window.MathJax = {
            tex    : {
              inlineMath: { '[+]': [['$', '$']] }
            },
            loader : {
              load: ['ui/lazy']
            },
            options: {
              renderActions: {
                insertedScript: [200, () => {
                  document.querySelectorAll('mjx-container').forEach(node => {
                    let target = node.parentNode;
                    if (target.nodeName.toLowerCase() === 'li') {
                      target.parentNode.classList.add('has-jax');
                    }
                  });
                }, '', false]
              }
            }
          };
        } else {
          MathJax.startup.document.state(0);
          MathJax.texReset();
          MathJax.typeset();
          MathJax.typesetPromise();
        }

        Fluid.events.registerRefreshCallback(function() {
          if ('MathJax' in window && MathJax.startup.document && typeof MathJax.startup.document.state === 'function') {
            MathJax.startup.document.state(0);
            MathJax.texReset();
            MathJax.typeset();
            MathJax.typesetPromise();
          }
        });
      </script>
    

  <script  src="https://lib.baomitu.com/mathjax/3.2.2/es5/tex-mml-chtml.js" ></script>

  <script  src="/js/local-search.js" ></script>

  <script defer src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js" ></script>





<!-- 主题的启动项，将它保持在最底部 -->
<!-- the boot of the theme, keep it at the bottom -->
<script  src="/js/boot.js" ></script>


  

  <noscript>
    <div class="noscript-warning">博客在允许 JavaScript 运行的环境下浏览效果更佳</div>
  </noscript>
</body>
</html>
